package system.util;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Hashtable;

import system.DebugOptionInterface;
import system.agent.AgentInterface;
import system.agent.CommunicationAgentInterface;

/* The starter class. It is loader by the class loader associated with the
   agent, thus ensuring that when the agent is deserialized, all the
   classes used by the agent are loader by this class loader.
 */

public class StarterImpl implements StarterInterface, DebugOptionInterface {


	@Override
	public CommunicationAgentInterface startAgent(Socket s) {
		try {
			//Create an object stream in order to deserialize the agent state.
			InputStream is = s.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);

			/* We must first deserialize the code of the agent since this code is itself used to
	       deserialize the agent data objects.
	       The code is loaded in the class loader by invoking the integrateCode() method.
			 */
			Hashtable cod = (Hashtable)ois.readObject();
			Loader l = (Loader)this.getClass().getClassLoader();
			l.integrateCode(cod);
			
			//Deserialize the agent objects. This may be any complex graph of objects.
			AgentInterface a = (AgentInterface)ois.readObject();
			s.close();
			if (OPTION) { 
				System.out.println ("Activation de l'agent " + a.getAgentName());
			}
			Server.registerAgent(a.getAgentName(), a);
			a.main();
			return a;

		} catch (Exception ex) {
			System.out.println("Starter(startAgent) error: " + ex.getMessage());
			ex.printStackTrace();
			return null;
		}
	}


}



